import React from "react";
import { Radio, Input, Checkbox } from "antd";
import Zcon from "@cbd/icon";
import { isEmpty } from "@cbd/utils";
import update from "immutability-helper";
import ExternalData from "./ExternalData";
import styles from "./OptionAdd.less";

import { openNotificationWithIcon, getUuid } from "../../../../../utils/comm";

const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;

class OptionAdd extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      optionsCache: [],
      checkValue: false,
      visible: false,
    };
    this.openNotificationWithIcon = openNotificationWithIcon;
  }

  componentDidMount() {
    const { selectedItem } = this.props;
    let checkboxValue = false;
    if (selectedItem.params) {
      // 若存在 params 字段，判断对象是否不是空对象
      checkboxValue = JSON.stringify(selectedItem.params) !== "{}";
    }

    this.setState({ checkValue: checkboxValue });
  }

  componentWillUnmount() {}

  onCheckboxChange = (e) => {
    // console.log(e);
    const { handleOptionsChange } = this.props;
    this.setState({ checkValue: e.target.checked, visible: e.target.checked });
    // 勾选外部数据
    if (e.target.checked) {
      handleOptionsChange({ options: [], params: {} });
    } else {
      const newItem = {
        key: getUuid(), // 用于页面操作
        id: "options1",
        name: "选项 1",
      };
      handleOptionsChange({ options: [newItem], params: {} });
    }
  };

  handleTaskVisible = (visible, clearData = false) => {
    const { handleOptionsChange } = this.props;
    this.setState({ visible });
    // console.log(clearData);
    if (clearData) {
      const newItem = {
        key: getUuid(), // 用于页面操作
        id: "options1",
        name: "选项 1",
      };
      handleOptionsChange({ options: [newItem], params: {} });
      this.setState({ checkValue: false });
    }
  };

  handleOpitonAdd = () => {
    const { onChange, options } = this.props;
    if (!onChange) return;
    if (options.length > 0 && options.some((item) => !item.id || !item.name)) {
      this.openNotificationWithIcon(
        "warning",
        "",
        `请先填写完选项的信息，再新增选项`,
      );
      return;
    }
    const newItem = {
      key: getUuid(), // 用于页面操作
      id: "",
      name: "",
    };
    const arr = [...options, newItem];
    onChange(arr);
  };

  handleOValueChange = (name, value, index, oldItem) => {
    const { optionsCache: stateOption } = this.state;
    const { options } = this.props;
    let optionsCache = [...stateOption];
    if (isEmpty(stateOption)) {
      optionsCache = [...options];
    }
    const newItem = {};
    newItem[name] = value;
    this.setState(
      update(
        { optionsCache },
        {
          optionsCache: {
            $splice: [
              [index, 1],
              [index, 0, { ...oldItem, ...newItem }],
            ],
          },
        },
      ),
    );
  };

  handleBlur = (name, value, index) => {
    const { onChange, options } = this.props;
    const { optionsCache: stateOption } = this.state;
    const isNotDiff = options.some((item, cindex) => {
      return cindex === index && item[name] === value;
    });
    if (isNotDiff) return;
    if (onChange) {
      this.setState({ optionsCache: [] });
      onChange(stateOption);
    }
  };

  onRadioChange = (e) => {
    const { multiple = false } = this.props;
    const { onDefaultChange } = this.props;
    if (!onDefaultChange) return;
    const resValue = multiple ? e : e.target.value;
    onDefaultChange(resValue);
  };

  handleDelete = (index) => {
    const { onChange, options, onDefaultChange, defaultValue } = this.props;
    const newOption = [...options];
    if (newOption[index].key === defaultValue && onDefaultChange) {
      setTimeout(() => {
        onDefaultChange(undefined);
      }, 30);
    }
    newOption.splice(index, 1);
    if (onChange) {
      this.setState({ optionsCache: [] });
      onChange(newOption);
    }
  };

  // 选项配置移动
  handleItemMove = (index, type = "up") => {
    const { options = [], onChange } = this.props;
    const { optionsCache } = this.state;
    const optionsArr = isEmpty(optionsCache) ? options : optionsCache;
    let newArr = optionsArr;
    let isUpdata = false;
    if (index !== 0 && type === "up") {
      newArr = update(optionsArr, {
        $splice: [
          [index - 1, 1],
          [index, 0, optionsArr[index - 1]],
        ],
      });
      isUpdata = true;
    } else if (index !== optionsArr.length - 1 && type === "down") {
      newArr = update(optionsArr, {
        $splice: [
          [index + 1, 1],
          [index, 0, optionsArr[index + 1]],
        ],
      });
      isUpdata = true;
    }
    if (!isUpdata) return;
    if (onChange) {
      onChange(newArr);
      this.setState({ optionsCache: [] });
    }
  };

  optionRender = (oitem, index, optionsArr) => {
    const { multiple = false } = this.props;
    return (
      <div key={`option${index}`} className={styles.option_item}>
        <div className={styles.item_con}>
          <span className={styles.item_title}>{`选项${index + 1}：`}</span>
          {multiple ? (
            <Checkbox value={oitem.key}>设为默认选项</Checkbox>
          ) : (
            <Radio value={oitem.key}>设为默认勾选</Radio>
          )}
        </div>
        <div className={styles.item_con}>
          <span
            className={`${styles.opration} 
        ${index === 0 && styles.up_disabled} 
        ${index === optionsArr.length - 1 && styles.down_disabled}`}
          >
            <Zcon
              type="arrow-up"
              onClick={() => this.handleItemMove(index, "up")}
            />
            <Zcon
              type="arrow-down"
              onClick={() => this.handleItemMove(index, "down")}
            />
          </span>
          <Input
            maxLength={15}
            placeholder="请输入选项名称"
            value={oitem.name}
            onChange={(e) =>
              this.handleOValueChange("name", e.target.value, index, oitem)
            }
            onBlur={(e) => this.handleBlur("name", e.target.value, index)}
          />
        </div>
        <div className={styles.item_con}>
          <span className={styles.opration}>
            <Zcon type="delete" onClick={() => this.handleDelete(index)} />
          </span>
          <Input
            maxLength={15}
            placeholder="请输入选项值"
            value={oitem.id}
            onChange={(e) =>
              this.handleOValueChange("id", e.target.value, index, oitem)
            }
            onBlur={(e) => this.handleBlur("id", e.target.value, index)}
          />
        </div>
      </div>
    );
  };

  render() {
    const {
      className = "",
      required = false,
      label,
      defaultValue = null,
      options = [],
      // onChange,
      // onDefaultChange,
      multiple = false,
      handleOptionsChange,
      selectedItem,
    } = this.props;
    const { optionsCache, checkValue, visible } = this.state;

    const optionsArr = isEmpty(optionsCache) ? options : optionsCache;

    let checkboxValue = false;
    if (selectedItem.params) {
      // 若存在 params 字段，判断对象是否不是空对象
      checkboxValue = JSON.stringify(selectedItem.params) !== "{}";
    }

    return (
      <div className={`${styles.option_add} ${className}`}>
        <div
          className={`item__lable ${required ? "item__lable_required" : ""} ${
            styles.lable
          }`}
        >
          {label}
          <Checkbox
            onChange={this.onCheckboxChange}
            checked={checkboxValue && checkValue}
            key="1"
          >
            外部数据
          </Checkbox>
          {checkboxValue && checkValue && (
            <span
              className={styles.review}
              onClick={() => this.handleTaskVisible(true)}
            >
              查看
            </span>
          )}
        </div>
        {!multiple ? (
          <RadioGroup onChange={this.onRadioChange} value={defaultValue}>
            {optionsArr.map((oitem, index) =>
              this.optionRender(oitem, index, optionsArr),
            )}
          </RadioGroup>
        ) : (
          <CheckboxGroup onChange={this.onRadioChange} value={defaultValue}>
            {optionsArr.map((oitem, index) =>
              this.optionRender(oitem, index, optionsArr),
            )}
          </CheckboxGroup>
        )}

        {!checkValue && (
          <div className={styles.option_btn} onClick={this.handleOpitonAdd}>
            <Zcon type="plus" />
            &nbsp;&nbsp;新增选项
          </div>
        )}
        {visible && (
          <ExternalData
            visible={visible}
            onCancel={this.handleTaskVisible}
            handleOptionsChange={handleOptionsChange}
            selectedItem={selectedItem}
          />
        )}
      </div>
    );
  }
}
export default OptionAdd;
